package net.chenlin.dp.modules.sys.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dingtalk.api.response.OapiSsoGetuserinfoResponse;
import com.taobao.api.ApiException;

import net.chenlin.dp.common.support.properties.DingtalkProperties;
import net.chenlin.dp.common.support.properties.GlobalProperties;
import net.chenlin.dp.common.utils.MD5Utils;
import net.chenlin.dp.common.utils.ShiroUtils;
import net.chenlin.dp.modules.sys.dingtalk.DingtalkUtils;
import net.chenlin.dp.modules.sys.entity.SysUserEntity;
import net.chenlin.dp.modules.sys.service.SysUserLinkerService;
import net.chenlin.dp.modules.sys.service.SysUserService;

/**
 * 钉钉链接应用方式，进入应用
 * @author lenovo
 *
 */
@Controller
public class DingtalkController extends AbstractController {

	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysUserLinkerService sysUserLinkerService;

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private DingtalkProperties dingtalkProperties;
	
	/**
	 * 跳转登录页面
	 * @return
	 */
	@RequestMapping(value = "/dingtalkAdmin", method = RequestMethod.GET)
	public String loginFromDingtalk(String lang, String nation,String code) {
		

		/* 通过钉钉应用处理认证  */
		try {
			String accessToken=DingtalkUtils.getAccessToken(dingtalkProperties.getCorpId(), dingtalkProperties.getSsoSecret());
			
			OapiSsoGetuserinfoResponse dingtalkUserinfo=DingtalkUtils.getUserInfo(accessToken,code);
			
			String dingtalkUserID= dingtalkUserinfo.getUserInfo().getUserid();
			
			SysUserEntity user=DingtalkUtils.getOrSaveSysUser(dingtalkUserinfo);
			
			// for test
			if (user==null) user=sysUserService.getByUserName("zhouyl");

			UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
			ShiroUtils.getSubject().login(token);
			SecurityUtils.getSubject().getSession().setAttribute("sessionFlag", true);
			return redirect("/");
			
		} catch (ApiException e) {
			e.printStackTrace();
		}

		if (ShiroUtils.isLogin() || ShiroUtils.getUserEntity() != null) {
			return redirect("/");
		}
		
		
		return redirect("/");
	}
	

}
